package cn.edu.hitwh.yibao.service.impl;

import cn.edu.hitwh.yibao.entity.Medicine;
import cn.edu.hitwh.yibao.form.MedicineForm;
import cn.edu.hitwh.yibao.mapper.MedicineMapper;
import cn.edu.hitwh.yibao.service.MedicineService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.util.List;

@Service
public class MedicineServiceImpl implements MedicineService {
    @Autowired
    private MedicineMapper medicineMapper;

    @Override
    public String select(MedicineForm medicineForm, Model model) {
        Medicine medicine = new Medicine();
        BeanUtils.copyProperties(medicineForm, medicine);
        List<Medicine> list = medicineMapper.selectList(medicine);
        model.addAttribute("medList", list);
        return "/medicine/select";
    }

    @Override
    public String add(MedicineForm medicineForm, Model model) {
        Medicine medicine = new Medicine();
        BeanUtils.copyProperties(medicineForm, medicine);
        int count = medicineMapper.insert(medicine);
        if (count > 0) {
            return "redirect:/medicine/addComplete";
        } else {
            model.addAttribute("addResult", "添加药品失败！");
            return "/medicine/select";
        }
    }

    @Override
    public String updateInit(String serId, Model model) {
        Medicine medicine = medicineMapper.selectById(serId);
        model.addAttribute("med", medicine);
        return "/medicine/update";
    }

    @Override
    public String update(MedicineForm medicineForm, Model model) {
        Medicine medicine = new Medicine();
        BeanUtils.copyProperties(medicineForm, medicine);
        int count = medicineMapper.update(medicine);
        if (count > 0) {
            return "redirect:/medicine/updateComplete";
        } else {
            return "/medicine/select";
        }
    }

    @Override
    public String delete(String serId, Model model) {
        int count = medicineMapper.delete(serId);
        if (count > 0) {
            return "redirect:/medicine/deleteComplete";
        } else {
            model.addAttribute("deleteResult", "删除药品失败！");
            return "/medicine/select";
        }
    }

    @Override
    public String detail(String serId, Model model) {
        Medicine medicine = medicineMapper.selectById(serId);
        model.addAttribute("med", medicine);
        return "/medicine/detail";
    }
}
